<?php


namespace app\index\controller;


use app\BaseController;
use app\common\model\Order;
use app\common\model\Wx_Pay_Record;
use think\App;
use think\Log;
use wxpay\WxPay;

class Notify extends BaseController
{
    protected $record;
    protected $order;

    public function __construct(App $app, Wx_Pay_Record $record, Order $order)
    {
        parent::__construct($app);
        $this->record = $record;
        $this->order = $order;
    }

    private function returnCode($returnCode)
    {
        $arr = [
            'return_code' => $returnCode,
            'return_msg' => 'OK',
        ];
        $xml = arrayToXml($arr);
        echo $xml;
        exit;
    }

    public function notify(Log $log)
    {
        $data = file_get_contents('php://input');
//        file_put_contents('a.txt' , $data);
//        $log->write('开始验证' . json_encode($data), 'error');
        $data = xmlToArray($data);
        if (empty($data) || empty($data['sign']) || $data['sign'] != WxPay::instance()->sign($data)) {
            $log->write('订单回调验证失败' . json_encode($data), 'error');
            exit;
        }
        if ($data['return_code'] == 'SUCCESS') {
//            $log->write('开始验证' . json_encode($data), 'error');
            $this->record->startTrans();
            try {
                $outTradeNo = $data['out_trade_no'];
                $record = $this->record->getOneByOutSn($outTradeNo);
                if (empty($record)) {
                    $this->returnCode('FAIL');
                }
                if ($record->pay_paid == 1) {
                    $this->record->commit();
                    $this->returnCode('SUCCESS');
                }
                $update = [
                    'id' => $record['id'],
                    'pay_paid' => 1,
                    'pay_paid_time' => strtotime($data['time_end']),
                    'pay_paid_amount' => $data['total_fee'],
                    'pay_paid_openid' => $data['openid'],
                    'pay_transid' => $data['transaction_id'],
                    'pay_modified_date' => time(),
                ];
                $rel = $this->record->update($update);
                if (!$rel) {
                    throw new \Exception('FAIL');
                }

                $order = $this->order->where('order_sn', $record['pay_order_sn'])->find();
                $order->status = 2;
                $order->pay_date = date('Y-m-d H:i:s');
                $order->save();

                $this->record->commit();
                $this->returnCode('SUCCESS');
            } catch (\Exception $e) {
                $log->write('订单处理失败' . $e->getMessage(), 'error');
                $this->record->rollback();
                $this->returnCode('FAIL');
            }
        }
        $this->returnCode('FAIL');
    }
}